#include <iostream>
#include <pthread.h>
#include <unistd.h>

const int num = 2;

pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;

void *Run(void *args)
{
    char *name = (char *)args;
    while (true)
    {
        pthread_mutex_lock(&gmutex);
        pthread_cond_wait(&gcond, &gmutex);
        std::cout << name<<"-我是"<<name << std::endl;
        pthread_mutex_unlock(&gmutex);
        //usleep(10000);
    }

    return nullptr;
}

int main()
{
    pthread_t thread[num];

    for (int i = 0; i < num; ++i)
    {
        char *buff = new char[1024];
        snprintf(buff, 1024, "thread-%d", i + 1);
        pthread_create(&thread[i], nullptr, Run, (void *)buff);
    }

    while (true)
        for (int i = 0; i < num; ++i)
        {
            sleep(1);
            // pthread_cond_signal(&gcond);
            pthread_cond_broadcast(&gcond);

            //usleep(100);
        }

    for (int i = 0; i < num; ++i)
    {
        pthread_join(thread[i], nullptr);
        std::cout << "join " << i + 1 << "success" << std::endl;
    }

    pthread_mutex_destroy(&gmutex);
    pthread_cond_destroy(&gcond);

    return 0;
}